package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import java.util.Set;
import java.util.HashSet;

/**
 * APP Token认证过滤器
 * 
 * @author ruoyi
 */
@Component
public class AppTokenAuthenticationFilter extends OncePerRequestFilter
{
    @Autowired
    private RedisCache redisCache;

    private static final String APP_TOKEN_KEY = "app_token:";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        String appToken = request.getHeader("App-Token");
        
        // 如果有App-Token且当前没有认证信息，尝试使用App-Token认证
        if (StringUtils.isNotEmpty(appToken) && SecurityContextHolder.getContext().getAuthentication() == null)
        {
            String tokenKey = APP_TOKEN_KEY + appToken;
            Object cacheObject = redisCache.getCacheObject(tokenKey);
            AppUser appUser = null;

            if (cacheObject instanceof AppUser) {
                appUser = (AppUser) cacheObject;
            } else if (cacheObject instanceof com.alibaba.fastjson2.JSONObject) {
                // 如果是JSONObject，转换为AppUser
                com.alibaba.fastjson2.JSONObject jsonObject = (com.alibaba.fastjson2.JSONObject) cacheObject;
                appUser = jsonObject.toJavaObject(AppUser.class);
            }
            
            if (appUser != null)
            {
                // 将APP用户转换为系统用户进行认证
                SysUser sysUser = convertAppUserToSysUser(appUser);

                // 为APP用户创建LoginUser，添加基本权限
                Set<String> permissions = new HashSet<>();
                
                // APP用户管理权限
                permissions.add("system:appuser:list");
                permissions.add("system:appuser:query");
                permissions.add("system:appuser:add");
                permissions.add("system:appuser:edit");
                permissions.add("system:appuser:remove");
                permissions.add("system:appuser:export");

                LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissions);

                UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        
        chain.doFilter(request, response);
    }

    /**
     * 将APP用户转换为系统用户
     */
    private SysUser convertAppUserToSysUser(AppUser appUser)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(appUser.getUserId());
        sysUser.setUserName(appUser.getPhone());
        sysUser.setNickName(appUser.getNickname());
        sysUser.setPhonenumber(appUser.getPhone());
        sysUser.setStatus(appUser.getStatus());
        sysUser.setDeptId(103L); // 设置一个默认部门ID
        return sysUser;
    }
}
